package com.los;

import java.util.Arrays;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * @program: java8
 * @description: stream特性之find
 * Optional<T>类(java.util.Optional)是一个容器类，代表一个值存在或不存在。
 * @author: Yujuan
 * @create: 2018-06-14 11:23
 **/
public class StreamFind {
    public static void main(String[] args) {
       Stream<Integer> integerStream= Arrays.stream(new Integer[]{1,2,3,4,5,6,7,8,9});

       //返回任意一个
        Optional<Integer> result=integerStream.filter(integer -> integer%2==0).findAny();
        System.out.println(result.get());

        //如果不存在则返回-1
        integerStream= Arrays.stream(new Integer[]{1,2,3,4,5,6,7,8,9});
        result=integerStream.filter(integer -> integer<0).findFirst();
        System.out.println(result.orElse(-1));

        //返回第一个
        integerStream= Arrays.stream(new Integer[]{1,2,3,4,5,6,7,8,9});
        result=integerStream.filter(integer -> integer%2==0).findFirst();
        //ifPresent是一个consumer，如果存在就打印
        result.ifPresent(System.out::println);
        System.out.println(result.get());

    }
}
